package motionsApp.client;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import com.google.gwt.user.client.rpc.AsyncCallback;

import motionsApp.shared.MotionDTO;

public class MotionsRepository {
	final private MotionsServiceAsync motionsService;
	private List<MotionsChangedCallback> listeners;
	private List<MotionDTO> motions;
	private boolean wereMotionsUpdated;

	public MotionsRepository(MotionsServiceAsync motionsService) {
		listeners = new ArrayList<MotionsChangedCallback>();
		this.motionsService = motionsService;
		motions = new ArrayList<MotionDTO>();
		refreshMotions(this.motionsService);
	}
	
	private void setMotions(final List<MotionDTO> result) {
		motions = result;
		for (MotionsChangedCallback listener : listeners) {
			listener.onChange(motions);
		}
	}

	private void refreshMotions(MotionsServiceAsync motionsService) {
		motionsService.getMotions(new AsyncCallback<List<MotionDTO>>() {			
			@Override
			public void onSuccess(final List<MotionDTO> result) {
				wereMotionsUpdated = true;
				setMotions(result);				
			}			
			
			@Override
			public void onFailure(final Throwable caught) {
				wereMotionsUpdated = true;
				setMotions(new ArrayList<MotionDTO>());				
			}
		});
	}
	
	public void registerListener(MotionsChangedCallback newListener){
		listeners.add(newListener);
		if(wereMotionsUpdated){
			newListener.onChange(motions);			
		}		
	}

	public void UpdateMotionLabels(MotionDTO motion, HashSet<String> newLabels) {
		MotionDTO updatedMoition = new MotionDTO(motion.getName(), newLabels);
		motionsService.updateMotion(updatedMoition, new AsyncCallback<Void>() {
			
			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		});
		
	}	
}